import com.google.jplurk.*
import org.cyberneko.html.parsers.*

words = ['天氣', 'weather', '氣象']

words.each {
	word ->
	
	if (plurk.content.toLowerCase().contains(word)) {
		println "match ${word}"
		
		ch_name = plurk.content.toLowerCase().replace(word, '').trim()
		println "查詢 ${ch_name}"
		
		def parser = new SAXParser()
		parser.setFeature('http://xml.org/sax/features/namespaces', false)
		page = new XmlParser(parser).parse('http://www.cwb.gov.tw/V6/forecast/taiwan/36-p1-data.htm')
		
		data = page.depthFirst().TR.grep {
			it.'@id' &&
			it.'@id'.endsWith('List') &&
			it.TD &&
			it.TD.A &&
			it.TD.A[0] &&
			it.TD.A[0].value() &&
			it.TD.A[0].value().contains(ch_name)
		}
		
		if (data) {
			data.each {
				if (it.TD.A[1] && it.TD.A[1].value()) {
					matched++
					ch_temp = it.TD.A[1].value()
					
					ch_pect = ''
					if (it.TD.A[2] && it.TD.A[2].value()) {
						ch_pect = it.TD.A[2].value()
					}
					
					ch_desc = ''
					if (it.TD.A[3] && it.TD.A[3].IMG && it.TD.A[3].IMG.'@title') {
						ch_desc = it.TD.A[3].IMG.'@title'
					}
					
					ship.response plurk.plurk_id, "${ch_name}氣溫${ch_temp}${ch_pect}${ch_desc}", Qualifier.SAYS
				}
			}
		}
		else {
			matched++
			ship.response plurk.plurk_id, "找不到 ${ch_name} 的天氣資料啦！", Qualifier.SAYS
		}
	}
}
